<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\common\model\Order as OrderModel;
use app\order\model\OrderInfo;
use app\user\model\Address;
use app\order\model\OrderGoodsExpress;
use app\order\model\OrderGoods as OrderGoodsModel;
use service\ApiReturn;
use think\Db;
use app\order\model\OrderPickup;


/**
 * 订单接口
 * Class UserLabel
 * @package app\api\controller\v1
 */
class Order extends Base
{
    /**
     * 获取支付方式列表
     * created: 2021/7/20 17:44
     */
    public function pay_type()
    {
        $res = Db::name('pay_type_list')
            ->where('status', 1)
            ->order('sort', 'desc')
            ->select();
        return ApiReturn::r(1, $res, 'ok');
    }

    /**
     * 创建订单
     * @author 晓风<215628355@qq.com>
     */
    public function add_order($data, $user)
    {
        $order_type = $data['order_type'];
        Db::startTrans();
        try {
            switch ($order_type) {
                case '1':
                    $order = OrderModel::addRechargeOrder($data, $user);
                    break;
                case '2':
                    $order = OrderModel::addRechargeOrder($data, $user);
                    break;
                case '3':
                    $order = OrderGoodsModel::addGoodsOrder($data, $user);
                    break;

                default:
                    throw new \Exception(lang('暂不支持该类型订单下单'));
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '', $e->getMessage());
        }
        if ($order) {
            return ApiReturn::r(1, $order, lang('下单成功，请向预支付接口获取支付信息'));
        }
        return ApiReturn::r(0, '', lang('下单失败'));
    }

    /**
     * 查询订单详情
     * @param $data
     * @param $user
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/23 19:14
     */
    public function get_order_detail($data, $user)
    {

        $order = OrderModel::where(['order_sn' => $data['order_sn'], 'user_id' => $user['id']])->find();
        if (!$order) {
            return ApiReturn::r(0, [], lang('无效订单号'));
        }
        if (in_array($order["order_type"], [1, 2])) {
            return ApiReturn::r(1, $order, lang('请求成功'));
        }

        $order['activity_type'] = 0;

        $time = time();
        //订单最大售后时限
        $order['refund_day'] = $refund_day = module_config('order.refund_day');
        $refund_max_time = $order['pay_time'] + $refund_day * 24 * 3600;

        //订单是否停止售后
        $order['stop_refund'] = (!in_array($order["status"], [1, 2, 3, 4, 5]) || ($order['pay_time'] > 0 && $refund_max_time < $time)) ? 1 : 0;
        //订单自动确认收货时限
        $order_receive = module_config('order.order_receive');

        $order['order_receive_time'] = $order['pay_time'] > 0 ? ($order['pay_time'] + $order_receive * 24 * 3600) : null;

        $order['pay_time'] = format_time($order['pay_time']);
        $order['pay_type'] = OrderModel::$payTypes[$order['pay_type']] ?? $order['pay_type'];
        $order['order_info'] = OrderInfo::get(['order_sn' => $order["order_sn"]]);
        $map = [];
        $map['order_sn'] = $order['order_sn'];
        if (isset($data['goods_id'])) {
            return ApiReturn::r(0, [], lang('接口已调整，请调用售后下单接口'));
        }
        //订单是否展示评价操作
        $order['show_review'] = 1;
        $receive_time = OrderGoodsExpress::where('order_sn', $order['order_sn'])->value('receive_time') ? : 0;
        $comment = Db::name('goods_comment')->where('order_sn', $order['order_sn'])->find();
        if ($receive_time <= 0 || $comment) $order['show_review'] = 0;
        $goods_list = OrderGoodsModel::where($map)->select();
        $goodIds =  [];
        foreach ($goods_list as &$item) {
            $goodIds[] = $item["goods_id"];
            $item['refund_info'] = $refund = \app\order\model\OrderRefund::field("id,status,refund_money,refund_type,num,is_delete")
                ->where('order_sn', $item['order_sn'])
                ->where('goods_id', $item['goods_id'])
                ->where('sku_id', $item['sku_id'])
                ->order('id', 'desc')
                ->find() ?: null;

            $item['goods_thumb'] = get_thumb($item['goods_thumb']);
            $item['nonrefundable'] = (in_array($item["order_status"], [1, 2, 3, 4]) && $time < $refund_max_time && bccomp($order['payable_money'], 0, 2) > 0) ? 0 : 1;

            $item['refund_id'] = $refund ? $refund['id'] : 0;
            $item['is_refund'] = $refund ? 0 : 1;
            $item['order_refund_status'] = $refund ? $refund['status'] : null;
            $item['goods_thumb'] = get_file_url($item['goods_thumb']);
            if ($receive_time <= 0 || $comment) $item['show_review'] = 0;
            if ($item['show_review'] == 1 && $order['show_review'] == 0) {
                $order['show_review'] = 1;
            }
        }
        unset($item);
        $order['order_goods_list'] = $goods_list;
        //积分抵扣显示
        $order['is_integral_reduce'] = 0;
        $hour = 6;

        $is_remind = Db::name('order_remind')->where([['order_sn', '=', $data['order_sn'], ['create_time', 'gt', (time() - $hour * 3600)]]])->find();
        $order['is_remind'] = $is_remind ? ['info' => 1, 'hour' => $hour] : ['info' => 0, 'hour' => $hour];

        //订单支付超时时间
        $order['cancel_time'] = bcadd(module_config('order.order_timeout') * 60, $order->getData("create_time"));

        $order['refund_day'] = $refund_day;

        //$order['refund_count'] = \app\order\model\OrderRefund::where(['order_sn'=>$order['order_sn']])->where("status","in",[0,1,2])->count(); 
        //查询未上架产品数量
        $nosale =  \app\goods\model\Goods::where("id",'in', array_unique($goodIds))->where('is_sale','neq',1)->count();
        
        $order['goods_is_sale'] = $nosale > 0 ?  0 : 1;

        //自提类型获取自提点信息，add by wangph at 2021-4-19
        if ($order['send_type'] == 1) {
            $order['pick_info'] = OrderPickup::getOrderPickUp($data['order_sn']);
            if (empty($order['order_info'])) {
                //自提备注替换order_goods_info表的remark,因为自提没写入order_goods_info表
                $order_info = [
                    'remark' => $order['pick_info']['remark']
                ];
                $order['order_info'] = $order_info;
            }
        }
        return ApiReturn::r(1, $order, lang('请求成功'));
    }

    //二维数组根据某字段去重
    public function array_unset($arr, $key)
    {
        $res = array();
        foreach ($arr as $value) {
            if (isset($res[$value[$key]])) {
                unset($value[$key]);
            } else {
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }

    /**
     * 获取订单列表
     * @param $data
     * @param $user
     */
    public function get_list($data, $user)
    {
        $userId = $user['id'];
        $type = $data['type'] ? $data['type'] : 'all';
        $map = [];
        switch ($type) {
            case 'unpay':
                $map[] = ['g.status', '=', 0];
                break;
            case 'unship':
                $map[] = ['g.status', '=', 1];
                break;
            case 'unreceive':
                $map[] = ['g.status', '=', 2];
                break;
            case 'finish':
                $map[] = ['g.status', '=', 3];
                break;
            case 'evaluate':
                $map[] = ['g.status', '=', 4];
                break;
            case 'cancel':
                $map[] = ['g.status', 'in',[-1,-2] ];
                break;
            default:
              
                break;
        }    
        $map[] = ['g.order_type', 'in',  [3, 5, 6, 7, 9, 10, 11]];
        
        $search = [];
        if ($data['search_name']) {
            $search[] = ['g.order_sn|ogi.receiver_name', 'like', '%' . $data['search_name'] . '%'];
            $search[] = ['g.order_sn', 'in', function ($query) use ($data) {
                $query->name('order_goods_list')->where('goods_name', 'like', '%' . $data['search_name'] . '%')->field("order_sn");
            }];

        }
        $map[] = ['g.user_id', '=', $userId];
        $map[] = ['g.is_delete', '=', 0];
       
        $list = OrderModel::alias("g")
            ->join("order_goods_info ogi", 'g.order_sn = ogi.order_sn', 'left')
            ->field('g.order_sn,g.cost_integral,g.send_type,status,payable_money,real_money,order_type,g.create_time,invoice_status,order_money,reduce_money,integral_reduce,pay_time')
            ->where($map)
            ->where(function ($query) use ($search) {
                $query->whereOr($search);
            })
            ->order('g.aid desc')
            ->paginate();

        $total = $list->total();
        $order = $list->items();
        $order_timeout = module_config('order.order_timeout');
        $refund_day = module_config('order.refund_day');
        $hour = 6;
        $time = time();
        $minTime = $time - $hour * 3600;
        foreach ($order as $k => $item) {
            $order[$k]['activity_type'] = 0;
            $order[$k]['sales_integral'] = $order[$k]['cost_integral'];

            $is_remind = Db::name('order_remind')->where([['order_sn', '=', $item['order_sn'], ['create_time', 'gt', $minTime]]])->find();
            $order[$k]['is_remind'] = $is_remind ? ['info' => 1, 'hour' => $hour] : ['info' => 0, 'hour' => $hour];

            //订单是否展示评价操作
            $item['show_review'] = 1;
            $receive_time = OrderGoodsExpress::where('order_sn', $item['order_sn'])->value('receive_time') ? : 0;
            $comment = Db::name('goods_comment')->where('order_sn', $order['order_sn'])->find();
            if ($receive_time <= 0 || $comment) $item['show_review'] = 0;

            $goods = OrderGoodsModel::where(['order_sn' => $item['order_sn']])->select();
            foreach ($goods as $ks => $g) {
                $order[$k]['is_pure_integral'] = $g['is_pure_integral'];
                $goods[$ks]['goods_thumb'] = get_thumb($g['goods_thumb']);
                $goods[$ks]['refund_info'] = \app\order\model\OrderRefund::field("id,status,refund_money,refund_type,num,is_delete")
                    ->where('order_sn', $item['order_sn'])
                    ->where('goods_id', $g['goods_id'])
                    ->where('sku_id', $g['sku_id'])
                    ->order('id', 'desc')
                    ->find() ?: null;

                $goods[$ks]['order_refund_status'] = $goods[$ks]['refund_info']['status'] ?? null;
                if ($receive_time <= 0 || $comment) $g['show_review'] = 0;
                // if ($g['show_review'] == 1 && $item['show_review'] == 0) {
                //     $item['show_review'] = 1;
                // }
            }
            $order[$k]['goods'] = $goods;
            $order[$k]['cancel_time'] = bcadd($order_timeout * 60, strtotime($item['create_time']));
            $order[$k]['refund_count'] = \app\order\model\OrderRefund::where(['order_sn' => $item['order_sn']])->where("status", "in", [0, 1, 2])->count();

            //订单是否停止售后
            $refundMaxTime = $item['pay_time'] + $refund_day * 24 * 3600;
            $order[$k]['stop_refund'] = (!in_array($item["status"], [1, 2, 3, 4, 5]) || ($item['pay_time'] > 0 && $refundMaxTime < $time)) ? 1 : 0;

            //chen add
            $order[$k]['is_integral_reduce'] = 0;
        }
        return ApiReturn::r(1, ['total' => $total, 'list' => $order], lang('订单列表'));
    }

    /**
     * 提醒发货
     * @param $data
     * @param $user
     */
    public function remind_order($data, $user)
    {

        // order_status = 1
        $order_sn = $data['order_sn'];
        // 判断订单是否可提醒
        $order = \think\Db::name('order')->where('order_sn', $order_sn)->where('status', 1)->find();
        if (!$order) {
            return ApiReturn::r(0, '', lang('已发货，请刷新订单'));
        }
        // 判断是否已提醒
        $remind = \think\Db::name('order_remind')->where('order_sn', $order_sn)->where('user_id', $user['id'])->find();
        if ($remind) {
            return ApiReturn::r(0, '', lang('已提醒'));
        }

        $idata = [
            'order_sn' => $data['order_sn'],
            'user_id' => $user['id'],
            'create_time' => time()
        ];
        $rs = \think\Db::name('order_remind')->insert($idata);
        if ($rs) {
            // 通知后端pc
            return ApiReturn::r(1, '', lang('提醒成功'));
        } else {
            return ApiReturn::r(0, '', lang('提醒失败'));
        }
    }

    /**
     * 确认收货
     * @param $data
     * @param $user
     */
    public function receive_order($data, $user)
    {

        try {
            $map[] = ["order_sn", "=", $data["order_sn"]];
            $map[] = ["status", "=", 2];
            $map[] = ["order_type", "in", [3,5,6]];
            $map[] = ["user_id", "=", $user["id"]];

            $order = \app\common\model\Order::where($map)->find();
            if (!$order) {
                throw new \Exception('订单不可操作，请刷新');
            }
            \app\order\model\OrderGoods::receiveOrder($order, 1);
        } catch (\Exception $e) {
            return ApiReturn::r(0, '', $e->getMessage());
        }
        return ApiReturn::r(1, '', '确认成功');
    }


    /**
     * 删除订单
     * @param $data
     * @param $user
     */
    public function remove_order($data, $user)
    {
        // order_status = 3,4,6 => -2
        $order_sn = $data['order_sn'];
        // 软删除
        Db::startTrans();
        try {
            $order = OrderModel::where('order_sn', $order_sn)->find();
            if (!$order) {
                exception('订单不可操作，请刷新');
            }
            $count = \app\order\model\OrderRefund::where(['order_sn' => $data['order_sn']])->where("status", "in", [0, 1, 2])->count();
            if ($count > 0) {
                throw new \Exception('订单有进行中的退款，请先处理退款');
            }
            OrderModel::where('order_sn', $order['order_sn'])->setField('is_delete', 1);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '', $e->getMessage());
        }
        return ApiReturn::r(1, '', '删除成功');
    }

    /**
     * 查看物流
     * @author 晓风<215628355@qq.com>
     * @date 2021年11月4日17:00:13
     */
    public function express($data, $user)
    {

        $order_sn = $data['order_sn'];
        $server_no = $data["server_no"];
        if ($server_no) {
            $express = \app\order\model\OrderRefund::where('server_no', $server_no)
                ->field('express_no,express_company_id,order_sn')
                ->where("express_no", "<>", "")
                ->find();
        } else {
            $express = \app\order\model\OrderGoodsExpress::where('order_sn', $order_sn)
                ->field('express_no,express_company_id,order_sn')
                ->find();
        }
        if (!$express) {
            return ApiReturn::r(0, '', lang('没有物流数据'));
        }

        $express_company = \app\goods\model\ExpressCompany::where("aid", $express['express_company_id'])->field("name,logo,tel,express_no")->find();

        $express_company["logo"] = $express_company["logo"] ? get_thumb($express_company["logo"]) : "";
        $ex = \app\order\model\OrderGoodsExpress::getQuery($express["express_no"], $express_company["express_no"], $express["order_sn"]);
        $ex["ShipperCode"] = $express_company['name'];
        $ex["logo"] = $express_company['logo'];
        return ApiReturn::r(1, $ex, lang('物流信息'));
    }

    /**
     * 再来一单-添加购物车
     * @param string $requests .order_sn 原订单号[必须]
     * @param string $requests .failure 检测商品是否失效[非必须|1检测0不检测直接排除无效商品]
     * @return \think\response\Json
     * @since 2020年9月1日12:00:49
     * @author zenghu [ 1427305236@qq.com ]
     */
    public function reorder($requests, $user)
    {
        // 接收再来一单参数
        $order_sn = $requests['order_sn'];

        // 查询订单信息
        $order = DB::name("order")->where(['order_sn' => $order_sn])->find();
        if (empty($order)) {
            return ApiReturn::r(0, [], '查无此单,请重新下单购买');
        }
        $orderGoodsList = DB::name("order_goods_list gl")
            ->field("
                gl.goods_id,gl.goods_name,gl.num,gl.sku_id,gl.sku_name,
                g.id,g.name,g.thumb,g.status,g.is_sale,g.is_delete,g.stock,g.shop_price,g.member_price
            ")
            ->join('goods g', 'gl.goods_id=g.id', 'left')
            ->where('order_sn', $order_sn)
            ->select();

        // 检测无效商品信息
        $failureGoodsList = []; // 无效商品信息
        if ($requests['failure'] == 1) {
            foreach ($orderGoodsList as $val) {
                // 如果商品不存在或状态不可用或售完或删除
                if (!$val["id"] || $val["status"] != 1 || $val["is_sale"] != 1 || $val["is_delete"] != 0) {
                    array_push($failureGoodsList, ['goods_id' => $val['id'], 'goods_name' => $val['name'], 'goods_thumb' => get_thumb($val['thumb'])]);
                    continue;
                }
                // 查询商品库存
                if ($val['sku_id'] > 0) { // 存在SKU
                    // 判断SKU信息
                    $sku = DB::name("goods_sku")->where(['sku_id' => $val['sku_id'], "goods_id" => $val['id']])->find();
                    if (!$sku || $sku["status"] != 1 || $sku["stock"] < 1) {
                        array_push($failureGoodsList, ['goods_id' => $val['id'], 'goods_name' => $val['name'], 'goods_thumb' => get_thumb($sku['spec_img'])]);
                        continue;
                    }
                } else { // 无SKU
                    $sku = DB::name("goods_sku")->where(["goods_id" => $val['id']])->find();
                    if (!$sku || $sku["status"] != 1 || $sku["stock"] < 1) {
                        array_push($failureGoodsList, ['goods_id' => $val['id'], 'goods_name' => $val['name'], 'goods_thumb' => get_thumb($val['thumb'])]);
                        continue;
                    }
                }
            }
        }

        // 检测无效商品信息
        if ($requests['failure'] == 1 && !empty($failureGoodsList)) {
            return ApiReturn::r(666, [
                'goodsCount' => count($orderGoodsList),
                'failureGoodsCount' => count($failureGoodsList),
                'failureGoodsList' => $failureGoodsList
            ], '以下商品卖光了,先将其他商品加入购物车?');
        }

        // 之前购物车商品置为不选择
        Db::name('goods_cart')->where('user_id', $order["user_id"])->update(["is_choose" => 0]);

        // 执行添加购物车
        foreach ($orderGoodsList as $val) {
            // 如果商品不存在或状态不可用或售完或删除
            if (!$val["id"] || $val["status"] != 1 || $val["is_sale"] != 1 || $val["is_delete"] != 0) {
                continue; // 直接跳过
            }

            // 查询商品库存
            if ($val['sku_id'] > 0) { // 存在SKU
                // SKU信息
                $sku = DB::name("goods_sku")->where(['sku_id' => $val['sku_id'], "goods_id" => $val['id']])->find();
                if (!$sku || $sku["status"] != 1 || $sku["stock"] < 1) {
                    continue; // 直接跳过
                }

                // 查询购物车条件
                $goodsCartWhere = array(
                    'user_id' => $order['user_id'],
                    'goods_id' => $val['id'],
                    'sku_id' => $val['sku_id']
                );
                $skuStock = $sku['stock'];

                // 组装添加购物车的参数信息
                $goodsCartParams1 = array(
                    'sku_id' => $sku["sku_id"],
                    'sku_name' => $sku['key_name'],
                    'shop_price' => $sku['shop_price'],
                    'member_price' => $sku['member_price'],
                    'goods_thumb' => $sku['spec_img'],
                );
            } else { // 无SKU
                /*
                $sku = DB::name("goods_sku")->where(["goods_id" => $val['id']])->find();
                if (!$sku || $sku["status"] != 1 || $sku["stock"] < 1) {
                    continue; // 直接跳过
                }                 
                */

                // 查询购物车条件
                $goodsCartWhere = array(
                    'user_id' => $order['user_id'],
                    'goods_id' => $val['id'],
                    'sku_id' => 0
                );
                $skuStock = $val['stock'];

                // 组装添加购物车的参数信息
                $goodsCartParams1 = array(
                    'sku_id' => 0,
                    'sku_name' => "",
                    'shop_price' => $val['shop_price'],
                    'member_price' => $val['member_price'],
                    'goods_thumb' => $val['thumb'],
                );
            }

            // 是否有相同的商品在购物车
            $info = Db::name('goods_cart')->field('id,num')->where($goodsCartWhere)->find();
            // 计算购买商品数量 如果大于剩余数量 只取sku剩余数量
            $goodsCartNum = !empty($info) ? ($info['num'] + $val['num']) : $val['num'];
            $goodsCartNum = ($goodsCartNum > $skuStock) ? $skuStock : $goodsCartNum;

            // 组装添加购物车的参数信息
            $goodsCartParams = array(
                'user_id' => $order["user_id"],
                'goods_id' => $val["id"],
                'goods_name' => $val['name'],
                "num" => $goodsCartNum,
                "is_choose" => 1
            );
            $goodsCartParams = array_merge($goodsCartParams, $goodsCartParams1);
            // 添加购物车
            if (!empty($info)) {
                Db::name('goods_cart')->where(['id' => $info['id']])->update($goodsCartParams);
            } else {
                Db::name('goods_cart')->insert($goodsCartParams);
            }
        }

        return ApiReturn::r(1, [], lang('加入购物车成功'));
    }

    /**
     * 提交单条评论
     * @param array $param
     */
    private function addOneComment($param, $user)
    {

        $param["content"] = $param["content"] ?: "买家很懒，什么都没有说";
        $param["star"] = $star = $param["star"] ?: 5;
        $param["type"] = $param["type"] ?: 0;
        $param["sku_id"] = $param["sku_id"] ?: 0;

        $res = $this->validate($param, \app\goods\validate\Comment::class);
        if (true !== $res) {
            throw new \Exception($res);
        }

        $order = OrderGoodsModel::where(['order_sn' => $param['order_sn'], 'goods_id' => $param['goods_id'], "sku_id" => $param["sku_id"]])
            ->find();
        if (!$order) {
            throw new \Exception('订单不可操作，请刷新');
        }
        $goods_comment = [
            "video" => $param["video"] ?: 0,
            'order_sn' => $param['order_sn'],
            'goods_id' => $param['goods_id'],
            'thumb' => is_array($param['thumb']) ? implode(',', $param['thumb']) : $param['thumb'],
            'user_id' => $user['id'],
            'star' => $param['star'],
            'content' => $param['content'],
            'create_time' => time(),
            'type' => empty($param['type']) ? 0 : 1,
            'sku_id' => $param['sku_id'],
            'sku_name' => $order['sku_name'],
            'pid' => empty($param['pid']) ? 0 : $param['pid'],
        ];
        $res = Db::name('goods_comment')->insert($goods_comment);
        if (!$res) {
            throw new \Exception('评论失败');
        }
        OrderGoodsModel::where("id", $order["id"])->update([
            "order_status" => 4,
            "is_evaluate" => 1
        ]);
        \app\goods\model\Goods::where('id', $param['goods_id'])->setInc('comment_count');
        return true;
    }

    /**
     * 订单评价
     * @param $data
     * @param $user
     */
    public function comment($data, $user)
    {

        Db::startTrans();
        try {
            $count = \app\order\model\OrderRefund::where(['order_sn' => $data['order_sn']])->where("status", "in", [0, 1, 2])->count();
            if ($count > 0) {
                throw new \Exception('订单有进行中的退款，请先处理退款');
            }

            if ($data["goods_comment"]) {
                $arr = json_decode($data['goods_comment'], true);
                if (!is_array($arr)) {
                    throw new \Exception('批量评论数据提交失败');
                }
                foreach ($arr as $param) {
                    $param["order_sn"] = $data['order_sn'];
                    $this->addOneComment($param, $user);
                }
            } else {
                $this->addOneComment($data, $user);
            }
            $order_goods = OrderGoodsModel::where('order_sn', $data['order_sn'])->where('order_status', 3)->find();
            if (!$order_goods) {
                OrderModel::where('order_sn', $data['order_sn'])->where('status', 3)->setField('status', 4);
                \app\order\model\OrderAction::addLog($data["order_sn"], "订单评论完成", 4, $user["id"]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '', $e->getMessage());
        }
        return ApiReturn::r(1, [], '评论成功');
    }


    /**
     * 订单角标
     * @author 上官琳 [ 2814356964@qq.com ]
     * @created 2020/2/17 11:02
     */
    public function orderNum($data = [], $user = [])
    {
        $result['no_pay'] = 0;
        $result['deliver'] = 0;
        $result['receiv'] = 0;
        $result['refund'] = 0;
        $result['evaluate'] = 0;
        $list = OrderModel::where('user_id', $user['id'])
            ->where('order_type', 'in', [3, 5, 6, 7, 9, 10, 11])
            ->where('is_delete', "<>", 1)
            ->field('count(order_sn) as num,status')
            ->group('status')
            ->select();

        foreach ($list as $k => $v) {
            if ($v['status'] == 0) {
                $result['no_pay'] = $v['num'];
            }
            if ($v['status'] == 1) {
                $result['deliver'] = $v['num'];
            }
            if ($v['status'] == 2) {
                $result['receiv'] = $v['num'];
            }
            if ($v['status'] == 3) {
                $result['evaluate'] = $v['num'];
            }
        }

        //修正未读消息数量
        $message = \app\operation\model\SystemMessage::getNoreadCount($user["id"]);      
        $article = \app\operation\model\Article::getNoticeNoread($user["id"]);
        $chats   = \app\customer\model\Session::where("user_id",$user["id"])->where("user_delete",0)->sum("user_noread");
        
        $result['msg_num'] =  $message + $article + $chats;
        return ApiReturn::r(1, $result, lang('查询成功'));
    }

    /**
     * 修改收货地址
     * @author zhougs
     * @createTime 2020年12月18日17:40:54
     */
    public function updateOrderAddress($data, $user)
    {
        if (!$data['order_sn'] || !$data['address_id']) {
            return ApiReturn::r(0, [], lang('参数错误'));
        }
        
        Db::startTrans();
        try {
            OrderInfo::editAddressId($data['order_sn'] , $data['address_id'] , $user["id"]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ApiReturn::r(0, '', $e->getMessage());
        }
        return ApiReturn::r(1, [], '修改成功');
    }

    /**
     * 物流公司
     * @author jxy [ 415782189@qq.com ]
     * @after 晓风<215628355@qq.com> 移动位置
     */
    public function get_express_company($data)
    {
        $map[] = ["status", "=", 1];
        if ($data["keyword"]) {
            $map[] = ["name|express_no", "like", "%" . $data["keyword"] . "%"];
        }
        $list = \app\goods\model\ExpressCompany::where($map)
            ->order("sort asc,express_no asc,aid desc")
            ->select()
            ->each(function ($item) {
                $item["logo"] = $item["logo"] ? get_thumb($item["logo"]) : "";
                return $item;
            });

        return ApiReturn::r(1, ['list' => $list], lang('请求成功'));
    }

}
